package com.zlm.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zlm.utils.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 郑
 */
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Map<String,Object> map = new HashMap<>();

        String token = request.getHeader("token");

        try {
            JWTUtil.verify(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg","token失效");
        }
        map.put("code",400);
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json");
        response.getWriter().write(json);
        return false;
    }
}
